import { ReactElement, useState, useEffect, useRef } from 'react'
import style from './index.module.less'
import { Skeleton, Space, Button, Modal, message } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { getInfoRequest, getListRequest, importAgainRequest, ErrorSchema } from './ajax'
import { awaitWrap, setSearch, getSearch } from '@js/tool'
import { useParams, useLocation } from 'react-router-dom'
import { InputBatchSchema } from '@components/schema/inputBatch'
import classNames from 'classnames'
import Table, { TableRef } from '@components/table'
import { CaseSchema } from '@components/schema/caseSchema'
import { ConditionSchema } from '@components/schema/condition'
import { getColumn } from './util'
import EditModal from './components/editModal'

const { confirm } = Modal

async function initInfo (id: string, setInfo: (v: InputBatchSchema) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getInfoRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    setInfo(d)
  }
}

async function initData (id: string, data: { [k: string]: any }, setDataSource: (v: CaseSchema[]) => void, setTotal: (v: number) => void, setLoading: (v: boolean) => void, setSuccesCount: (v: number) => void, setErrors: (v: ErrorSchema[]) => void): Promise<void> {
  const condition: ConditionSchema[] = []
  let page = 1
  let limit = 10
  if (typeof data.status === 'string' && ['0', '1'].includes(data.status)) {
    condition.push({ k: 'status', o: '=', v: data.status })
  } else {
    condition.push({ k: 'status', o: '=', v: 1 })
  }
  if (typeof data.type === 'string') {
    condition.push({ k: 'fail_type', o: '=', v: data.type })
  }
  if (typeof data.page === 'number') {
    page = data.page
  }
  if (typeof data.limit === 'number') {
    limit = data.limit
  }
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(id, { condition, page, limit }))
  setLoading(false)
  if (e === null && d !== null) {
    setTotal(d.total)
    setDataSource(d.list)
    setSuccesCount(d.success_count)
    setErrors(d.failinfo)
  }
}

// 重新导入二次提醒
function confrimAgain (id: string, refreshData: () => void): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '您确定要重新导入失败案件吗？',
    onOk: () => {
      importAgain(id, refreshData).catch(e => console.error(e))
    }
  })
}

async function importAgain (id: string, refreshData: () => void): Promise<void> {
  const hide = message.loading('导入中')
  const [e] = await awaitWrap(importAgainRequest(id))
  hide()
  if (e === null) {
    message.success('导入成功').then(null, null)
    refreshData()
  }
}

interface Props {
  meta: {
    id: string
  }
}

function Main ({ meta }: Props): ReactElement {
  const l = useLocation()
  const tableRef = useRef<TableRef>(null)
  const [info, setInfo] = useState<InputBatchSchema | null>(null)
  const [infoLoading, setInfoLoading] = useState(false)
  const [otherBread, setOtherBread] = useState<Array<{ name: string, url?: string }>>([{ name: '批量导入案件', url: '/admin/case-input-batch' }, { name: '导入结果' }])
  const [status, setStatus] = useState(1)
  const [loading, setLoading] = useState(false)
  const [total, setTotal] = useState(0)
  const [dataSource, setDataSource] = useState<CaseSchema[]>([])
  const [modifyData, setModifyData] = useState<CaseSchema | null>(null)
  const [successCount, setSuccesCount] = useState(0)
  const [errors, setErrors] = useState<ErrorSchema[]>([])
  const [visible, setVisible] = useState(false)
  const [params, setParams] = useState<{[k: string]: any}>({})
  useEffect(() => {
    if (typeof meta.id === 'string') {
      initInfo(meta.id, setInfo, setInfoLoading).catch(e => console.error(e))
    }
  }, [meta])
  useEffect(() => {
    if (info !== null) {
      setOtherBread([{ name: '批量导入案件', url: '/admin/case-input-batch' }, { name: '导入结果' }, { name: info.filename }])
    }
  }, [info])
  useEffect(() => {
    if (l !== null) {
      const s = getSearch()
      if (typeof s.status === 'string' && /^\d$/.test(s.status)) {
        setStatus(parseInt(s.status))
      } else {
        setStatus(1)
      }
    }
  }, [l])
  return (
    <div className={style.container}>
      <EditModal visible={visible} data={modifyData} hide={() => { setModifyData(null); setVisible(false) }} refreshData={() => tableRef.current?.refreshData()} />
      <div className={style.body}>
        <div className={style.info}>
          <Skeleton active loading={infoLoading}>
            <div className={style['info-cell']}>
              <div className={style['info-cell-title']}>已导入案件</div>
              <div className={style['info-cell-value']}><a onClick={() => setParams({...params, status: 1, page: 1, type: undefined })}>{successCount}</a></div>
            </div>
            {
              errors.map((li, i) => {
                return (
                  <div className={style['info-cell']} key={i}>
                    <div className={style['info-cell-title']}>{li.fail_type}</div>
                    <div className={classNames(style['info-cell-value'], style['info-error'])}><a onClick={() => setParams({ ...params, status: 0, page: 1, type: li.fail_type })}>{li.c}</a></div>
                  </div>
                )
              })
            }
          </Skeleton>
        </div>
        <div className={style.table}>
          { status === 0 && (<div className={style['table-notice']}>以下为批量导入失败的案件列表，可编辑进行修改</div>) }
            <Table rowKey='id' params={params} setParams={setParams} ref={tableRef} columns={getColumn(status === 0, setModifyData, setVisible)} loading={loading} total={total} dataSource={dataSource} onChange={async d => {
              await initData(meta.id, d, setDataSource, setTotal, setLoading, setSuccesCount, setErrors)
            }} />
        </div>
        {
          status === 0 && (
            <div className={style.footer}>
              <Space>
                <Button type='primary' disabled={dataSource.length === 0} onClick={() => confrimAgain(meta.id, () => tableRef.current?.refreshData())}>确定导入</Button>
              </Space>
            </div>
          )
        }
      </div>
    </div>
  )
}

export default Main
